package com.atguigu.eduservice.service.impl;
import com.atguigu.eduservice.entity.Danw;
import com.atguigu.eduservice.mapper.DwMapper;
import com.atguigu.eduservice.service.DwService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component
public class DwServiceImpl extends ServiceImpl<DwMapper, Danw> implements DwService {
    @Override
    public Map getOrg() {

        List<Danw> danws = baseMapper.selectList(null);
        //根据getYijName分组，得到所有分组后的key（key就是一级机构的名称）和所有一级分类下面的集合

        Map<String, List<Danw>> map1 = danws.stream().collect(Collectors.groupingBy(Danw::getYijName));
        System.out.println("map1"+ map1);
        Map<String,Map<String,List<Danw>>> taotalMap = Maps.newHashMap();

        for(String yijName : map1.keySet()) {
            List<Danw> erjdanws = map1.get(yijName);
            taotalMap.put(yijName,erjdanws.stream().collect(Collectors.groupingBy(Danw::getErjName)));
        }
        int index = 1;
        Map<String,String> nameCodeMap = Maps.newHashMap();
        Map<String,Object> map = Maps.newHashMap();
        for (String yijdw : taotalMap.keySet()) {
            String code = getCode(index++ +"");
//            System.out.println(yijdw +" "+code);
            nameCodeMap.put(yijdw,code);
//            nameCodeMap.put(yijdw,"0");
            Map<String,List<Danw>> erjMap = taotalMap.get(yijdw);
            int erjIndex = 1;
            for (String erjdw : erjMap.keySet()) {
                String erjcode = nameCodeMap.get(yijdw)+getCode(erjIndex++ +"");
                System.out.println(erjdw +" "+erjcode);
                nameCodeMap.put(erjdw,erjcode);
//                nameCodeMap.put(erjdw+"1",nameCodeMap.get(yijdw));
                int sanjIndex = 1;
                List<Danw> sanjdws = erjMap.get(erjdw);
                if (CollectionUtils.isNotEmpty(sanjdws)) {
                    for (Danw sanjdw : sanjdws) {
                        if(StringUtils.isNotEmpty(sanjdw.getDanjName())){
                            String sanjcode = nameCodeMap.get(sanjdw.getErjName()) + getCode(sanjIndex++ + "");
//                            System.out.println(sanjdw.getDanjName() + " " + sanjcode);
                            nameCodeMap.put(sanjdw.getDanjName(), sanjcode);
//                            nameCodeMap.put(sanjdw.getDanjName()+"1",nameCodeMap.get(sanjdw.getErjName()));
                        }

                    }
                }
            }
        }
        return nameCodeMap;

    }

    private String getCode (String code) {
        return StringUtils.leftPad(code,3, "0");
    }
}
